<template>
  <div>
    <!--    1-->
    <!--    123-->
    <!--&lt;!&ndash;    123&ndash;&gt;-->
    <!--    123-->
    <!-- <el-breadcrumb separator="/" class="beeadBox" v-if="types==null">
      <el-breadcrumb-item
        class="breadItem"
        v-for="(item,index) in topInputList"
        :key="index"
      >
        <span  @click="backStor(index,item.id)">{{item.title}}</span>
      </el-breadcrumb-item>
    </el-breadcrumb> -->
    <el-button type="primary" icon="el-icon-plus" class="topAdd" @click="add"
      >添加</el-button
    >

    <div class="body">
      <el-tabs type="border-card" @tab-click="chooseTab">
        <el-tab-pane v-for="(item, index) in typeList" :key="index">
          <span :label="item" slot="label"
            >{{ item }}<i class="el-icon-date"></i>
          </span>
        </el-tab-pane>
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          max-height="550"
          border
          fit
        >
          <el-table-column
            show-overflow-tooltip
            prop="id"
            label="ID"
            width="90"
          >
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="sort"
            label="排序"
            width="90"
          >
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="name" label="名称">
            <template slot-scope="scope">
              <p :class="dropdownindex == 0 ? 'lanse' : ''">
                {{ scope.row.name }}
              </p>
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="image"
            label="图片"
            width="100"
            v-if="dropdownindex == 0 && topInputList.length > 1"
          >
            <template slot-scope="scope">
              <el-image
                style="width: 50px; height: 50px"
                :src="imgHeader + scope.row.image"
                fit="cover"
                :preview-src-list="[imgHeader + scope.row.image]"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="types"
            label="类型"
            v-if="dropdownindex != 0"
            width="150"
          >
            <template slot-scope="scope">
              <p>{{ scope.row.types_text }}</p>
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            :label="dropdownindex != 0 ? '默认' : '前台显示'"
            width="110"
          >
            <template slot-scope="scope">
              <el-switch
                v-if="types != null"
                v-model="scope.row.moren"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="默认"
                inactive-text=""
                active-value="1"
                :inactive-value="null"
                @change="switchChange(scope.row)"
              >
              </el-switch>
              <el-switch
                v-else
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="显示"
                inactive-text=""
                :active-value="1"
                :inactive-value="2"
                @change="switchChange3(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="默认" width="160">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="deleteObj(scope.$index, scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tabs>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="diaClose"
    >
      <el-form
        v-if="types != null"
        :hide-required-asterisk="true"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="名称：" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input v-model.number="ruleForm.sort"></el-input>
        </el-form-item>
        <el-form-item label="是否默认：" prop="moren">
          <el-switch
            v-model="ruleForm.moren"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="默认"
            inactive-text=""
            active-value="1"
            :inactive-value="null"
            @change="switchChange2(ruleForm.moren)"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="类别：" prop="type">
          <el-dropdown trigger="click" @command="chooseType">
            <el-button @click="selectDropdown">
              {{ typeList[dropdownindex]
              }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="(item, index) in typeList"
                :key="index"
                :command="index"
                >{{ item }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <el-form-item label="类型：" prop="type" v-if="dropdownindex != 0">
          <el-dropdown trigger="click" @command="chooseTypes">
            <el-button @click="selectDropdown">
              {{ toolTypes[dropdownTypesList].name
              }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="(item, index) in toolTypes"
                :key="index"
                :command="index"
                >{{ item.name }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="!submitFormflag"
            @click="submitForm('ruleForm')"
            >{{ dialogTitle == "添加" ? "立即创建" : "保存" }}</el-button
          >

          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>

      <el-form
        v-else
        label-position="right"
        label-width="80px"
        :model="formLabelAlign"
        :rules="formLabelAlignRules"
        ref="formLabelAlignruleForm"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input
            v-model="formLabelAlign.name"
            style="width: 100px"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="atavar">
          <div class="unlodBox">
            <el-upload
              class="upload-demo"
              action
              :http-request="uploadFile"
              ref="upload"
              :limit="fileLimit"
              :on-remove="handleRemove"
              :file-list="fileList"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :headers="headers"
            >
              <el-button size="mini" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过5M
              </div>
            </el-upload>
            <el-image
              style="width: 100px; height: 100px"
              :src="formLabelAlign.atavar"
              fit="cover"
            ></el-image>
          </div>
        </el-form-item>
        <el-form-item label="">
          <span style="">图标尺寸建议：60px*60px</span>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input
            v-model="formLabelAlign.sort"
            type="number"
            style="width: 100px"
          ></el-input>
        </el-form-item>
        <div>
          <el-button @click="closeVisible('formLabelAlignruleForm')"
            >取 消</el-button
          >
          <el-button type="primary" @click="save('formLabelAlignruleForm')"
            >保 存</el-button
          >
        </div>
      </el-form>
    </el-dialog>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50, 60]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>

<script>
import {
  toolList,
  toolAdd,
  toolSet,
  toolDelete,
  goodsSonSort,
  addSort,
  uploadFilec,
  setSort,
  deleteSort,
  goodsSort,
} from "../../utils/api";

export default {
  name: "toolList",
  data() {
    var checkAge = (rule, value, callback) => {
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
          // callback(new Error(typeof value));
        } else {
          if (value < 0) {
            callback(new Error("必须大于0"));
          } else {
            callback();
          }
        }
      }, 300);
    };
    return {
      token: sessionStorage.getItem("token"),
      submitFormflag: true,
      tableData: [],
      currentPage: 1,
      limit: 10,
      total: 0,
      loading: false,
      typeList: ["维修项目", "维修工具"],
      dropdownindex: 0,
      type: 1,
      dialogTitle: "添加",
      dialogVisible: false,
      ruleForm: {
        name: "",
        moren: null,
        type: 1,
        sort: 100,
      },
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "change" }],
        sort: [{ validator: checkAge, trigger: "change" }],
      },
      formLabelAlignRules: {
        atavar: [{ required: true, message: "请上传图片", trigger: "change" }],
        name: [{ required: true, message: "请输入名称", trigger: "change" }],
        sort: [{ required: true, message: "排序不能为空", trigger: "change" }],
      },
      types: null,
      toolTypes: [
        { name: "水", type: 0 },
        { name: "木", type: 1 },
        { name: "油", type: 2 },
        { name: "瓦", type: 3 },
        { name: "电", type: 4 },
      ],
      dropdownTypesList: 0,
      formLabelAlign: {
        name: "",
        sort: "",
        atavar: "",
        avatar: "",
        id: "",
        parent_id: 0,
        status: "",
      },
      fenleiList: [],
      fenleiListvalue: "",
      fenleiListProps: {
        label: "name",
        value: "id",
        children: "child",
        checkStrictly: true,
      },
      imgHeader: this.Global.imgHeader,

      fileList: [],
      fileType: ["png", "jpg", "jpeg"],
      fileLimit: 1,
      headers: { "Content-Type": "multipart/form-data" },
      topInputList: [{ title: "根分类", id: 0 }],
    };
  },
  created() {
    if (this.types == null) {
      this.goodsSonSort();
    } else {
      this.toolList(this.type, this.types);
    }
  },
  watch: {
    type(n, o) {
      console.log(n);
      this.ruleForm.type = n;
      this.dropdownindex = n - 1;
    },
  },
  methods: {
    backStor(index, id) {
      this.topInputList.splice(index + 1);
      this.goodsSonSort();
    },
    optinochange(e) {
      console.log(123123);
    },
    handleRemove() {},
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    uploadFile(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      uploadFilec(item.file).then((res) => {
        if (res.data.status != false || res.data.id != null) {
          res.data.data.saveurl; //半截
          res.data.data.weburl; //全拼
          this.formLabelAlign.atavar = res.data.data.weburl;
          this.formLabelAlign.avatar = res.data.data.saveurl;
          this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
          let i = this.fileList.indexOf(item.file);
          this.handleSuccess();
        }
      });
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClose();
    },
    //这是我自定义的移除事件
    handleClose(i) {
      this.fileList.splice(i, 1); //删除上传的文件
    },
    cascader1Change(e) {},
    chooseType(command) {
      this.dropdownindex = command;
      this.ruleForm.type = command + 1;
    },
    chooseTypes(command) {
      console.log(command);
      this.dropdownTypesList = command;
      this.types = command;
    },
    // 下拉框
    selectDropdown() {},
    // 提交表单
    submitForm(formName) {
      if (!this.submitFormflag) {
        return;
      }
      this.submitFormflag = false;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          console.log(this.ruleForm);
          if (this.dialogTitle == "添加") {
            console.log(this.types);
            this.toolAdd();
          } else if (this.dialogTitle == "编辑") {
            this.toolSet();
          }
        } else {
          console.log("error submit!!");
          this.submitFormflag = true;
          return false;
        }
      });
    },

    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    closeVisible(e) {
      this.dialogVisible = false;
      this.$refs["formLabelAlignruleForm"].resetFields();
      this.formLabelAlign = {
        name: "",
        sort: "",
        atavar: "",
        avatar: "",
        id: "",
        parent_id: 0,
        status: "",
      };
    },
    save(formName) {
      console.log(this.formLabelAlign);

      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle == "添加") {
            addSort(
              this.token,
              this.formLabelAlign.parent_id,
              this.formLabelAlign.name,
              this.formLabelAlign.sort,
              this.formLabelAlign.avatar,
              1,
              2
            ).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "保存成功",
                  type: "success",
                });
                this.dialogVisible = false;
                this.$refs["formLabelAlignruleForm"].resetFields();
                this.goodsSonSort();
                this.formLabelAlign = {
                  name: "",
                  sort: "",
                  atavar: "",
                  avatar: "",
                  id: "",
                  parent_id: 0,
                  status: "",
                };
              } else {
                this.$message.error(res.data.msg);
              }
            });
          } else {
            setSort(
              this.token,
              this.formLabelAlign.parent_id,
              this.formLabelAlign.id,
              this.formLabelAlign.name,
              this.formLabelAlign.sort,
              this.formLabelAlign.avatar,
              this.formLabelAlign.status,
              2
            ).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "保存成功",
                  type: "success",
                });
                this.dialogVisible = false;
                this.$refs["formLabelAlignruleForm"].resetFields();
                this.goodsSonSort();
              }
            });
          }
        } else {
          console.log("error submit!!");
          this.submitFormflag = true;
          return false;
        }
      });
    },
    // 关闭dialog
    diaClose() {
      if (this.types != null) {
        this.dialogVisible = false;
        this.submitFormflag = true;
        this.types = 0;
        this.ruleForm = {
          name: "",
          moren: null,
          type: this.type,
          sort: 100,
        };
        this.$refs["ruleForm"].resetFields();
      } else {
        this.dialogVisible = false;
        this.$refs["formLabelAlignruleForm"].resetFields();
        this.formLabelAlign = {
          name: "",
          sort: "",
          atavar: "",
          avatar: "",
          id: "",
          parent_id: 0,
          status: "",
        };
      }
    },
    // 编辑类目
    handleEdit(index, row) {
      if (this.types == null) {
        this.dialogTitle = "编辑";
        this.dialogVisible = true;
        console.log(row);
        this.formLabelAlign = {
          name: row.name,
          sort: row.sort,
          atavar: row.aimages[0],
          avatar: row.image,
          id: row.id,
          parent_id: row.parent_id,
          status: row.status,
        };
      } else {
        this.dialogTitle = "编辑";
        console.log(index, row);
        this.ruleForm = {
          name: row.name,
          moren: row.moren,
          type: row.type,
          sort: row.sort,
          id: row.id,
        };
        this.dialogVisible = true;
      }
    },
    // 删除类目
    deleteObj(index, row) {
      this.$confirm("确认删除类目吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (this.types == null) {
            deleteSort(this.token, row.id)
              .then((res) => {
                if (res.data.status) {
                  this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                  this.goodsSonSort();
                } else {
                  this.$message.error(res.data.msg);
                }
              })
              .catch((err) => {
                console.log(err.message);
              });
          } else {
            toolDelete(this.token, row.id).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "删除成功",
                  type: "success",
                });
                this.toolList(this.type, this.types);
              } else {
                this.$message({
                  message: res.data.msg,
                });
              }
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 是否默认
    switchChange(row) {
      console.log(row);
      this.loading = true;
      toolSet(this.token, row.id, row.name, row.type, row.moren, row.sort).then(
        (res) => {
          let timer = setTimeout(() => {
            this.loading = false;
            clearTimeout(timer);
          }, 400);
        }
      );
    },
    switchChange3(row) {
      let img = "";
      img = row.image ? row.image : "";
      setSort(
        this.token,
        row.parent_id,
        row.id,
        row.name,
        row.sort,
        img,
        row.status,
        2
      ).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.goodsSonSort();
        }
      });
    },
    switchChange2(row) {},
    // 选择头部tab
    chooseTab(tab, event) {
      if (Number(tab.index) == 0) {
        this.goodsSonSort();
        this.types = null;
        this.type = 1;
      } else {
        this.type = Number(tab.index) + 1;
        this.types = 0;
        if (Number(tab.index) == 0) {
          this.types = null;
        }
        this.toolList(this.type, this.types);
      }
    },
    // 一页有几条
    handleSizeChange(val) {
      this.limit = val;
      this.toolList(this.type, this.types);
    },
    // 第几页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.toolList(this.type, this.types);
    },
    // 添加
    add() {
      this.dialogTitle = "添加";
      this.dialogVisible = true;
    },
    // 添加接口
    toolAdd() {
      toolAdd(
        this.token,
        this.ruleForm.name,
        this.ruleForm.moren,
        this.ruleForm.type,
        this.ruleForm.sort,
        this.types
      ).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          this.ruleForm = {
            name: "",
            moren: null,
            type: this.type,
            sort: 100,
          };
          this.$refs["ruleForm"].resetFields();
          this.dialogVisible = false;
          this.toolList(this.type, this.types);
        } else {
          this.$message({
            message: res.data.msg,
          });
        }
        this.submitFormflag = true;
      });
    },
    // 编辑接口
    toolSet() {
      toolSet(
        this.token,
        this.ruleForm.id,
        this.ruleForm.name,
        this.ruleForm.type,
        this.ruleForm.moren,
        this.ruleForm.sort,
        this.types
      ).then((res) => {
        console.log(res);
        if (res.data.status) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.ruleForm = {
            name: "",
            moren: null,
            type: this.type,
            sort: 100,
          };
          this.$refs["ruleForm"].resetFields();
          this.dialogVisible = false;
          this.toolList(this.type, this.types);
        } else {
          this.$message({
            message: res.data.msg,
          });
        }
        this.submitFormflag = true;
      });
    },
    // 请求接口
    toolList(type, types) {
      this.loading = true;
      toolList(this.token, this.currentPage, this.limit, type, types).then(
        (res) => {
          if (res.data.status) {
            this.tableData = res.data.data.data;
            this.total = res.data.data.count;
            this.tableData.forEach((item) => {
              if (item.types == 0) {
                item.types_text = "水";
              }
              if (item.types == 1) {
                item.types_text = "木";
              }
              if (item.types == 2) {
                item.types_text = "油";
              }
              if (item.types == 3) {
                item.types_text = "瓦";
              }
              if (item.types == 4) {
                item.types_text = "电";
              }
            });
            let timer = setTimeout(() => {
              this.loading = false;
              clearTimeout(timer);
            }, 400);
          } else {
            this.$message({
              message: res.data.msg,
            });
            let timer = setTimeout(() => {
              this.loading = false;
              clearTimeout(timer);
            }, 400);
          }
        }
      );
    },
    goodsSonSort() {
      this.loading = true;
      this.fenleiList = [];
      goodsSonSort(
        this.token,
        this.currentPage,
        this.limit,
        this.topInputList[this.topInputList.length - 1].id,
        2
      ).then((res) => {
        if (res.data.status) {
          this.tableData = res.data.data;
          this.total = res.data.count;
          //status 1显示  2不显示   type

          this.tableData.forEach((item) => {
            item.aimages = [];
            if (item.image) {
              item.aimages.push(this.imgHeader + item.image);
            }
          });

          let timer = setTimeout(() => {
            this.loading = false;
            clearTimeout(timer);
          }, 400);
          goodsSort(this.token, this.currentPage, this.limit, 2).then((res) => {
            if (res.data.status) {
              let list = res.data.data;
              list.forEach((item) => {
                this.fenleiList.push({
                  id: item.id,
                  name: item.name,
                });
              });
              this.fenleiList.unshift({
                id: 0,
                name: "顶级分类",
              });
            }
          });
        } else {
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
          }
          this.$message.error(res.data.msg);
          this.loading = false;
        }
      });
    },
  },
};
</script>

<style scoped>
.topAdd {
  margin: 10px;
}

/deep/ .el-tabs--border-card > .el-tabs__content {
  padding: 0;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
/deep/.upload-demo .el-upload--text {
  border: none;
  width: auto;
  height: auto;
}
.upload-demo {
  line-height: normal;
  margin-bottom: 20px;
}
.lanse {
  color: #409eff;
  cursor: pointer;
}
.beeadBox {
  margin: 10px auto;
  width: 95%;
}
.breadItem:hover {
  cursor: pointer;
}
</style>
